package com.security.brows.ui

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.text.format.Formatter
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.core.content.FileProvider
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import coil.compose.AsyncImage
import com.hub.videobrowsdownload.BrowsApplication
import com.hub.videobrowsdownload.BrowsM3U8Helper
import com.hub.videobrowsdownload.R
import com.security.brows.room.BrowsVideoDownloadBean
import com.security.brows.values.SecurityBrowsColorsScheme
import com.security.brows.values.SecurityBrowsDrawable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.net.URLConnection

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ComposeVpDownloaded(
    downloadedVideoList: State<List<BrowsVideoDownloadBean>>,
    colorsScheme: SecurityBrowsColorsScheme,
    drawableScheme: SecurityBrowsDrawable,
    state: LazyListState,
    displayItemTitle: MutableState<Int>
) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val totalMemorySize = remember {
        mutableStateOf(0L)
    }
    val usedMemorySize = remember {
        mutableStateOf(0L)
    }
    val availableMemorySize = remember {
        mutableStateOf(0L)
    }
    LaunchedEffect(Unit) {
        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
            // onResume 时调用的方法
            try {
                val file = BrowsM3U8Helper.getDownloadFileParentDir(context, 0)
                try {
                    val statFs = StatFs(file.path)
                    val blockSizeLong = statFs.blockSizeLong
                    val blockCountLong = statFs.blockCountLong
                    val size = blockCountLong * blockSizeLong
                    totalMemorySize.value = size
                } catch (e: Exception) {
                }

                try {
                    val statFs = StatFs(file.path)
                    val blockSizeLong = statFs.blockSizeLong
                    val blockCountLong = statFs.blockCountLong
                    val size = blockCountLong * blockSizeLong

                    val availableBlocksLong = statFs.availableBlocksLong
                    val available = availableBlocksLong * blockSizeLong
                    availableMemorySize.value = available
                    val used = size - available
                    usedMemorySize.value = used
                } catch (e: Exception) {
                }
            } catch (e: Exception) {
            }
        }
    }
    Box(modifier = Modifier.fillMaxSize()) {
        if (downloadedVideoList.value.size <= 0) {
            Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
                Image(
                    painter = painterResource(id = drawableScheme.no_pending),
                    contentDescription = null,
                    modifier = Modifier
                        .padding(horizontal = 80.dp)
                        .fillMaxWidth(),
                    contentScale = ContentScale.FillWidth
                )

                Spacer(modifier = Modifier.height(13.dp))

                Image(
                    painter = painterResource(id = drawableScheme.how_to_download),
                    contentDescription = null,
                    modifier = Modifier
                        .padding(top = 64.dp, start = 60.dp, end = 60.dp)
                        .fillMaxWidth()
                        .clickable(interactionSource = remember {
                            MutableInteractionSource()
                        }, indication = rememberRipple()) {
                            SecurityBrowsGuideActivity.start(context)
                        },
                    contentScale = ContentScale.FillWidth
                )

            }
        } else {

            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                state = state,
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {

                items(downloadedVideoList.value, key = { it.id }) { downloadedBean ->
                    val showPopupMenu = remember {
                        mutableStateOf(false)
                    }



                    Row(
                        Modifier
                            .animateItemPlacement()
                            .clip(RoundedCornerShape(10.dp))
                            .fillMaxWidth()
                            .height(88.dp)
                            .background(colorsScheme.browsBg, RoundedCornerShape(10.dp))
                            .combinedClickable(interactionSource = remember {
                                MutableInteractionSource()
                            }, indication = rememberRipple(), onLongClick = {
                                if (context.packageName.contains("downloadbrowsing")) {
                                    try {
                                        val file = File(downloadedBean.downloadFilePath)
                                        val uri = FileProvider.getUriForFile(
                                            context,
                                            context.packageName,
                                            file
                                        )

                                        val intent = Intent(Intent.ACTION_SEND)
                                        var MIME_TYPE: String? = null
                                        MIME_TYPE = try {
                                            URLConnection.guessContentTypeFromName(file.name)
                                        } catch (e: java.lang.Exception) {
                                            "*/*"
                                        }
                                        intent.type = MIME_TYPE
                                        intent.putExtra(Intent.EXTRA_STREAM, uri)
                                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

                                        context.startActivity(Intent.createChooser(intent, "Share"))
                                    } catch (e: Exception) {
                                    }
                                }
                            }) {

                                try {
                                    Log.i(
                                        "打开下载的视频",
                                        downloadedBean.downloadFilePath.toString()
                                    )
                                    val file = File(downloadedBean.downloadFilePath)
                                    val uri = FileProvider.getUriForFile(
                                        context,
                                        context.packageName,
                                        file
                                    )

                                    val intent = Intent(Intent.ACTION_VIEW)
                                    var MIME_TYPE: String? = null
                                    MIME_TYPE = try {
                                        "video/*"
                                    } catch (e: java.lang.Exception) {
                                        "*/*"
                                    }
                                    intent.type = MIME_TYPE
                                    intent.setDataAndType(uri, MIME_TYPE)
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)

                                    context.startActivity(intent)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }) {
                        Box(
                            Modifier
                                .padding(8.dp)
                                .fillMaxHeight()
                                .aspectRatio(110f / 72f, true)
                        ) {
                            AsyncImage(
                                model = downloadedBean.thumbPath,
                                contentDescription = null,
                                modifier = Modifier
                                    .clip(RoundedCornerShape(12.dp))
                                    .fillMaxSize(),
                                contentScale = ContentScale.Crop
                            )
                            Image(
                                painter = painterResource(id = drawableScheme.sheet_video_play),
                                contentDescription = null,
                                modifier = Modifier
                                    .align(
                                        Alignment.Center
                                    )
                                    .size(20.dp)
                            )
                            if ((downloadedBean.videoDuration ?: 0.0) > 0) {
                                val totalSeconds =
                                    if (downloadedBean.isM3U8) (downloadedBean.videoDuration
                                        ?: 0.0) else ((downloadedBean.videoDuration
                                        ?: 0.0) / 1000)
                                val hours = totalSeconds / 3600
                                val minutes = (totalSeconds % 3600) / 60
                                val seconds = totalSeconds % 60
                                Text(
                                    modifier = Modifier
                                        .padding(7.dp)
                                        .align(Alignment.BottomStart),
                                    text = String.format(
                                        "%02d:%02d:%02d",
                                        hours.toInt(),
                                        minutes.toInt(),
                                        seconds.toInt()
                                    ),
                                    fontSize = 11.sp,
                                    color = colorsScheme.sheetVideoDuration
                                )
                            }
                        }

                        Column(
                            Modifier
                                .align(Alignment.CenterVertically)
                                .weight(1f)
                        ) {

                            Text(
                                text = if (displayItemTitle.value == 1) downloadedBean.title else {
                                    downloadedBean.fileName ?: downloadedBean.title
                                }
                                    ?: "",
                                fontSize = 16.sp,
                                color = colorsScheme.sheetVideoTitle,
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            var text =
                                " "
                            if (downloadedBean.videoWidth != 0 && downloadedBean.videoHeight != 0) {
                                text =
                                    "${downloadedBean.videoWidth}X${downloadedBean.videoHeight}"
                            }
                            Box(modifier = Modifier.fillMaxWidth()) {

                                Text(
                                    text = text,
                                    fontSize = 14.sp,
                                    color = colorsScheme.sheetVideoResolution,
                                    modifier = Modifier.align(Alignment.CenterStart)
                                )

                                if (downloadedBean.videoLength != null && downloadedBean.videoLength!! > 0) {
                                    Text(
                                        modifier = Modifier
                                            .align(Alignment.CenterEnd),
                                        text = Formatter.formatFileSize(
                                            context,
                                            downloadedBean.getVideoFileSize()!!
                                        ).replace(" ", ""),
                                        fontSize = 14.sp,
                                        color = colorsScheme.sheetVideoSize
                                    )
                                }
                            }
                        }
                        Spacer(modifier = Modifier.width(8.dp))
                        Box(
                            modifier = Modifier
                                .fillMaxHeight()
                                .width(36.dp)
                                .clickable(interactionSource = remember {
                                    MutableInteractionSource()
                                }, indication = rememberRipple()) {
                                    showPopupMenu.value = true
                                }
                        ) {
                            Image(
                                painter = painterResource(id = drawableScheme.video_menu),
                                contentDescription = null,
                                modifier = Modifier
                                    .align(
                                        Alignment.Center
                                    )
                                    .size(20.dp)
                            )

                            if (showPopupMenu.value) {
                                PopCompose(
                                    showPopupMenu,
                                    drawableScheme,
                                    colorsScheme,
                                    downloadedBean
                                )
                            }
                        }

                    }
                }

                item { Spacer(modifier = Modifier.height(50.dp)) }

            }
        }

        Row(
            Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .background(colorsScheme.homeTabBg),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                modifier = Modifier.padding(vertical = 2.dp),
                text = "Used: ${
                    Formatter.formatFileSize(context, usedMemorySize.value).replace(" ", "")
                }, Available:  ${
                    Formatter.formatFileSize(context, availableMemorySize.value).replace(" ", "")
                }",
                fontSize = 12.sp,
                color = colorsScheme.homeTable
            )
        }
    }
}


@Composable
private fun PopCompose(
    showPopupMenu: MutableState<Boolean>,
    drawableScheme: SecurityBrowsDrawable,
    colorsScheme: SecurityBrowsColorsScheme,
    downloadedBean: BrowsVideoDownloadBean
) {
    val context = LocalContext.current
    BackHandler(showPopupMenu.value) {
        showPopupMenu.value = false
    }

    val offsetX = with(LocalDensity.current) { 8.dp.toPx() }
    val offsetY = with(LocalDensity.current) { 8.dp.toPx() }
    Popup(offset = IntOffset(-offsetX.toInt(), offsetY.toInt()),
        alignment = Alignment.TopEnd,
        onDismissRequest = { showPopupMenu.value = false }) {
        Column(
            Modifier
                .width(56.dp)
                .border(1.dp, color = colorsScheme.homeTitleSpace, RoundedCornerShape(6.dp))
                .background(color = colorsScheme.browsBg, RoundedCornerShape(6.dp))
        ) {
            Box(modifier = Modifier
                .size(56.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    if (!downloadedBean.webUrl.isNullOrEmpty()) {
                        SecurityBrowsTabWebActivity.start(
                            context,
                            downloadedBean.webUrl
                        )
                    }
                }) {

                Image(
                    painter = painterResource(id = drawableScheme.video_web),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(20.dp),
                    contentScale = ContentScale.FillBounds
                )
            }
            Box(modifier = Modifier
                .size(56.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    BrowsApplication.browsMyViewModel.rmDownloaded(
                        context,
                        downloadedBean
                    )
                }) {

                Image(
                    painter = painterResource(id = drawableScheme.video_delete),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(20.dp),
                    contentScale = ContentScale.FillBounds
                )
            }

            Box(modifier = Modifier
                .size(56.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    if (!downloadedBean.webUrl.isNullOrEmpty()) {
                        SecurityBrowsTabWebActivity.startSafari(
                            context,
                            downloadedBean.webUrl!!
                        )
                    }
                }) {

                Image(
                    painter = painterResource(id = R.drawable.brows_safari_icon),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(20.dp),
                    contentScale = ContentScale.FillBounds
                )
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

                Box(modifier = Modifier
                    .size(56.dp)
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        if (!downloadedBean.downloadFilePath.isNullOrEmpty()) {
                            Toast
                                .makeText(context, "Saving...", Toast.LENGTH_SHORT)
                                .show()
                            showPopupMenu.value = false

                            val it = File(downloadedBean.downloadFilePath!!)

                            if (it.exists() && it.length() > 0) {
                                CoroutineScope(Dispatchers.IO).launch {
                                    BrowsApplication.browsMyViewModel.saveFileToSdcard(
                                        BrowsApplication.context,
                                        it,
                                        "DownloadHub"
                                    )
                                }
                            }
                        }
                    }) {

                    Image(
                        painter = painterResource(id = R.drawable.brows_gallery),
                        contentDescription = null,
                        modifier = Modifier
                            .align(Alignment.Center)
                            .size(20.dp),
                        contentScale = ContentScale.FillBounds
                    )
                }
            }

        }
    }
}